﻿using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Dtos;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 根据采购/委外订单编号获取订单行信息
    /// </summary>
    public class SearchOrderBankHandler : IRequestHandler<SearchOrderBankCommand, Result<PageResultDto<OrderBankDto>>>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchOrderBankHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public SearchOrderBankHandler(ISqlSugarClient db,
            ILogger<SearchOrderBankHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 根据采购/委外订单编号获取订单行信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<OrderBankDto>>> Handle(SearchOrderBankCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<OrderBankDto>>() { Code = (int)CommonErrorCode.Search };
            //实例化分页
            var page = new PageResultDto<OrderBankDto>() { TotalCount = 0, PageCount = 0, List = new List<OrderBankDto>() };
            try
            {
                //总条数
                RefAsync<int> totalCount = 0;
                //总页数
                RefAsync<int> totalPage = 0;
                var query = _db.Queryable<OrderBanks, MaterialManagement, Units>((o, m, u) => o.MaterialId == m.MaterialId && o.UnitId == u.UnitId)
                    .Select((o, m, u) => new OrderBankDto()
                    {
                        OrderBankId = o.OrderBankId,
                        MaterialId = o.MaterialId,
                        Unitprice = o.Unitprice,
                        Quantity = o.Quantity,
                        UnitId = o.UnitId,
                        BankAmount = o.BankAmount,
                        Abstract = o.Abstract,
                        PurchaseNumber = o.PurchaseNumber,
                        CreatedOwner = o.CreatedOwner,
                        CreatedTime = o.CreatedTime,
                        UpdateOwner = o.UpdateOwner,
                        UpdateTime = o.UpdateTime,
                        ExamineOwner = o.ExamineOwner,
                        ExamineTime = o.ExamineTime,
                        MaterialCode = m.MaterialCode,
                        MaterialName = m.MaterialName,
                        UnitName = u.UnitName,
                    });
                //订单编码不为空
                if (!string.IsNullOrEmpty(request.PurchaseNumber))
                {
                    query = query.Where(o => o.PurchaseNumber == request.PurchaseNumber);
                }
                //分页
                var list = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                //总条数
                page.TotalCount = totalCount;
                //总页数
                page.PageCount = totalPage;
                //显示
                page.List = list;
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "根据采购/委外订单编号获取订单行信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "根据采购/委外订单编号获取订单行信息异常" + ex.Message;
                _logger.LogError("根据采购/委外订单编号获取订单行信息异常" + ex.Message);
            }
            return result;
        }
    }
}
